import axios, {
  AxiosInstance,
  AxiosError,
  AxiosRequestConfig,
  InternalAxiosRequestConfig,
  AxiosResponse,
} from "axios";
import { ResultData, GatewayResultData } from "@/api/interface";
import { ResultEnum } from "@/enums/httpEnum";
import { checkStatus } from "./helper/checkStatus";
import { ElMessage, ElMessageBox } from "element-plus";
import { userStore } from "@/store/modules/user";
export const LOGIN_URL: string = "/login";
import router from "@/router";
import qs from "qs";
const config = {
  // 默认地址请求地址，可在 .env.*** 文件中修改
  baseURL: import.meta.env.VITE_API_URL as string,
  // 设置超时时间（10s）
  timeout: ResultEnum.TIMEOUT as number,
  // 跨域时候允许携带凭证
  withCredentials: true,
};

class RequestHttp {
  service: AxiosInstance;
  public constructor(config: AxiosRequestConfig) {
    // 实例化axios
    this.service = axios.create(config);
	
    /**
     * @description 请求拦截器
     * 客户端发送请求 -> [请求拦截器] -> 服务器
     * token校验(JWT) : 接受服务器返回的token,存储到vuex/pinia/本地储存当中
     */
    this.service.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        const userStores = userStore();
        const token = userStores.token;
        if (config.headers && typeof config.headers?.set === "function")
          config.headers.set("Authorization", token);
        return config;
      },
      (error: AxiosError) => {
        return Promise.reject(error);
      }
    );

    /**
     * @description 响应
     *  服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
     */
    this.service.interceptors.response.use(
      (response: AxiosResponse) => {
        const { data } = response;
        const userStores = userStore();
        // * 登陆失效（code == 401）
        if (data.code == ResultEnum.OVERDUE) {
          if (document.getElementsByClassName("el-message").length == 0) {
            ElMessage.error(data.msg);
            //错误提示
          }
          userStores.changeToken("");
          router.replace(LOGIN_URL);
          return Promise.reject(data);
        }
        // * 全局错误信息拦截（防止下载文件得时候返回数据流，没有code，直接报错）
        if (data.code && data.code !== ResultEnum.SUCCESS) {
          if (data.code > 200 && data.code < 300) {
            ElMessage.warning(data.msg);
          } else {
            if (data.code !== 502) {
              ElMessage.error(data.msg);
            }
          }
          return Promise.reject(data);
        }
        return data;
      },
      async (error: AxiosError) => {
        const { response } = error;
        const { data, code } = (response?.data as any) || {};
        if (code == 400) {
          let arr = [];
          for (let v in data) {
            arr.push(data[v]);
          }
          ElMessageBox.alert(arr.join("</br>"), "错误", {
            confirmButtonText: "确认",
            dangerouslyUseHTMLString: true,
          });
          return Promise.reject();
        }
        if (response?.config?.url === "auth/token/login") {
          return { data: response.data };
        }
        // 上传失败如果不return 不进el-upload的on-error
        if (
          response?.config?.url === "/resource/file/uploadFiles" ||
          response?.config?.url === "/dems-resource/file/uploadFile"
        ) {
          return { data: response?.data };
        }
        // 请求超时 && 网络错误单独判断，没有 response
        if (error.message.indexOf("timeout") !== -1)
          ElMessage.error("请求超时！请您稍后重试");
        if (error.message.indexOf("Network Error") !== -1)
          ElMessage.error("网络错误！请您稍后重试");
        // 根据响应的错误状态码，做不同的处理
        if (response && response.data) {
          let data = <any>response.data;
          let obj = data.body ?? data;
          if ("msg" in obj) {
            ElMessage.error(obj.msg);
          } else {
            checkStatus(response.status);
          }
        } else if (response) {
          checkStatus(response.status);
        }
        // * 登陆失效（code == 401）
        if (response?.status == ResultEnum.OVERDUE) {
          if (document.getElementsByClassName("el-message").length == 0) {
            ElMessage.error(data.msg);
            //错误提示
          }
          const userStores = userStore();
          userStores.changeToken("");
          router.replace(LOGIN_URL);
        }
        // 服务器结果都没有返回(可能服务器错误可能客户端断网)，断网处理:可以跳转到断网页面
        if (!window.navigator.onLine) router.replace("/500");
        return Promise.reject(error);
      }
    );
  }

  // * 常用请求方法封装
  get<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
    return this.service.get(url, { params, ..._object });
  }
  post<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
    return this.service.post(url, qs.stringify(params), _object);
  }
  postJson<T>(
    url: string,
    params?: object,
    _object = {}
  ): Promise<ResultData<T>> {
    return this.service.post(url, params, _object);
  }
  put<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
    return this.service.put(url, params, _object);
  }
  delete<T>(url: string, params?: any, _object = {}): Promise<ResultData<T>> {
    return this.service.delete(url, { params, ..._object });
  }
  download(url: string, params?: object, _object = {}): Promise<BlobPart> {
    return this.service.get(url, {
      params,
      ..._object,
      responseType: "blob",
      timeout: 0,
    });
  }
  getRequest<T>(
    url: string,
    params?: object,
    _object = {}
  ): Promise<GatewayResultData<T>> {
    return this.service.get(url, { params, ..._object });
  }
  upload<T>(
    url: string,
    params?: object,
    _object = {}
  ): Promise<ResultData<T>> {
    return this.service.post(url, params, { ..._object, timeout: 0 });
  }
}

export default new RequestHttp(config);
